package net.maku.framework.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
public class WeiXinUtils {

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public static String getOpenId(String code, String appId, String secret) {
        Map<String, String> params = new HashMap<>(16);
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("grant_type", "authorization_code");
        params.put("js_code", code);

        String result = HttpGetUtil.httpRequestToString(ACCESS_TOKEN_URL, params);
        log.info("wx openid:{}", result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    public static String getAccessToken(String appId, String secret) {
        //这里需要换成你d的小程序appid
        //这里需要换成你的小程序secret
        //获取微信ACCESS_TOKEN 的Url
        String accent_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        String url = accent_token_url.replace("APPID", appId).replace("APPSECRET", secret);
        //发送请求
        String result = HttpGetUtil.httpRequestToString(url,null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.get("access_token").toString();
    }
}
